package view.micro.background
{
	import flash.display.MovieClip;
	import flash.display.Shape;
	import flash.display.Sprite;
	import util.Random;
	import util.Settings;
	import view.AnimatedSprite;
	import view.micro.IMicroSprite;
	
	/**
	 */
	public class BirdSprite extends AnimatedSprite implements IMicroSprite
	{
		
		private var xspeed:Number;
		
		static private const N_FRAMES:Number = 20;
		static private const MIN_SPEED:Number = 7 * Settings.METER;
		static private const MAX_SPEED:Number = 12 * Settings.METER;
		static private const LOOP_POINT:Number = 800;
		static private const FLAP_YSPEED:Number = 2.5 * Settings.METER;
		static private const FALL_YSPEED:Number = 0.7 * Settings.METER;
		static private const FALL_XACCEL:Number = -0.01 * Settings.METER;
		static private const FLAP_XACCEL:Number = 0.005 * Settings.METER;
		static private const FLAP_CHANCE:Number = 1.5;
		static private const FRAME_TIME:Number = 1 / 60.0;
		
		public function BirdSprite()
		{
			super(N_FRAMES);
			x = Random.integer(0, 500);
			y = Random.normal(325, 70);
			
			xspeed = Random.uniform(MIN_SPEED, MAX_SPEED);
			
			for (var i:int = 0; i < N_FRAMES / 2; i++)
			{
				var wy:Number = -0.7 * Settings.METER * (i - N_FRAMES / 2) / N_FRAMES;
				frames[i].graphics.lineStyle(0.02 * Settings.METER);
				frames[i].graphics.lineTo(-0.4 * Settings.METER, wy);
				frames[i].graphics.moveTo(0, 0);
				frames[i].graphics.lineTo(0.4 * Settings.METER, wy);
			}
			
			for (i; i < N_FRAMES; i++)
			{
				wy = 0.7 * Settings.METER * (i - N_FRAMES / 2) / N_FRAMES;
				frames[i].graphics.lineStyle(0.02 * Settings.METER);
				frames[i].graphics.lineTo(-0.4 * Settings.METER, wy);
				frames[i].graphics.moveTo(0, 0);
				frames[i].graphics.lineTo(0.4 * Settings.METER, wy);
			}
		}
		
		public function update():void
		{
			var timestep:Number = Settings.getTimeStep();
			x += xspeed * timestep;
			if (Math.random() < FLAP_CHANCE * timestep || current_frame != 1)
			{
				// cycle through frames properly for framerate
				var n:Number = FRAME_TIME / timestep;
				while (n > 0 && current_frame != 1)
				{
					n--;
					nextFrame();
				}
				if (Math.random() < n)
				{
					nextFrame();
				}
				
				y += FLAP_YSPEED * timestep;
				xspeed += FLAP_XACCEL * timestep;
			}
			else
			{
				y -= FALL_YSPEED * timestep;
				xspeed += FALL_XACCEL * timestep;
			}
			
			if (x > LOOP_POINT)
			{
				x -= LOOP_POINT + 50;
				y = Random.normal(325, 70);
				xspeed = Random.uniform(MIN_SPEED, MAX_SPEED);
			}
		}
		
		public function readyToRemove():Boolean
		{
			return false;
		}
	
	}

}